/*  File Name	: ProcessManager.h
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-6-29
 *  Description:
 */

#ifndef PROCESSMANAGER_H_
#define PROCESSMANAGER_H_

#include "EventHandler.h"

class Process
{
public:
	Process(std::string type,int line);

	virtual ~Process();

	int spawn(char *path,char *argv[]=NULL,std::string working_dir="",bool inherit_env=true);

	int terminate(int sig=9);

	const int pid(void);

	const int line(void);

	std::string type(void);

	EventHandler* notify_handler(EventHandler* eh=NULL);
private:
	int child_id_;
	int line_;
	std::string type_;
	EventHandler *notify_exit_;
};

/////////////////////////////////////////////

struct ProcessDescriptor
{
	ProcessDescriptor()
	{
		exit_handler_ = NULL;
		process_ = NULL;
	}
	Process *process_;
	EventHandler *exit_handler_;
};

///////////////////////////////////////////////////////

class ProcessManager:virtual public EventHandler
{
public:
	typedef std::map<pid_t,Process*> ProcessMap;

	typedef std::map<pid_t,EventHandler*> NotifyMap;

	ProcessManager(Reactor *reactor=NULL);

	virtual ~ProcessManager();

	int open(Reactor *reactor=NULL);

	int spawn(char *program,char *argv[]=NULL,std::string working_dir="./",bool inherit_env=true);

	int stop_all_child_process(void);

	int terminate(pid_t pid,int sig);

	Process* find_process(int pid);

	int remove_process(int pid);

	virtual int handle_signal(int signum);

	int register_handler(EventHandler *eh,int pid);

	//return exit process pid
	int wait(void);

	int has_child(void);
private:
	ProcessMap process_map_;
	RT_MUTEX rt_mutex_;
};

#endif /* PROCESSMANAGER_H_ */
